package com.yang.inventorymanagement.controllerview.suppliers;

import com.yang.inventorymanagement.comment.TableComponent;
import com.yang.inventorymanagement.pojo.Suppliers;
import com.yang.inventorymanagement.service.SuppliersService;
import com.yang.inventorymanagement.utils.SpringContextUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


@Lazy
@Scope("prototype")
@Component("SuppliersManageSwing")
/**
 * 供应商管理
 */
public class SuppliersManageSwing extends JPanel {


    private JTextField suppliersSelectField;

    private JTextField suppliersIdUpdate;
    private JTextField suppliersName;
    private JTextField suppliersEmailField;
    private JTextField suppliersContactName;

    private TableComponent table;
    private JButton flushBtn;


    // 表格数据
    private Object[] columnNames = {"供应商名称", "供应商联系人姓名", "供应商邮箱", "供应商识别代码"};
    private Object[][] rowData;


    private SuppliersService suppliersService = SpringContextUtils.getBean(SuppliersService.class);


    public SuppliersManageSwing() {
        setBounds(0, 0, 1165, 730);
        setLayout(null);
        JButton userAddBtn = new JButton("添加供应商");
        // 添加供应商
        userAddBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SupplierAddManageSwing frame = SpringContextUtils.getBean("SupplierAddManageSwing", SupplierAddManageSwing.class);
          /*      // 设置关闭操作的回调
                // 添加关闭监听器
                frame.addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent e) {
                        flushBtn.doClick();
                    }
                });*/
                frame.setVisible(true);

            }

        });
        userAddBtn.setBounds(10, 10, 93, 23);
        add(userAddBtn);


        /**
         * 刷新按钮
         */
        flushBtn = new JButton("刷新");
        flushBtn.setBounds(127, 10, 80, 23);

        // 刷新
        flushBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("刷新");
                updateSuppliersList(0, null);
            }
        });
        add(flushBtn);

        /**
         * 搜索框，搜索按钮
         */
        suppliersSelectField = new JTextField();
        suppliersSelectField.setBounds(236, 11, 389, 22);
        add(suppliersSelectField);
        suppliersSelectField.setColumns(10);

        JButton searchBtn = new JButton("供应商名称搜索");
        searchBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //获取搜索框信息
                String input = suppliersSelectField.getText();
                //数据校验
                if (input == null || "".equals(input.trim())) {
                    JOptionPane.showMessageDialog(null, "输入不能为空", "提示", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                //更新用户列表
                updateSuppliersList(1, input);
            }
        });
        searchBtn.setBounds(635, 10, 121, 23);
        add(searchBtn);


        JPanel suppliersListPanel = new JPanel();
        suppliersListPanel.setBorder(BorderFactory.createTitledBorder("用户列表"));
        suppliersListPanel.setBounds(10, 54, 746, 661);
        add(suppliersListPanel);

        // 设置表格数据
        rowData = suppliersService.getAllSuppliers();


        // 创建一个表格，指定 所有行数据 和 表头
        table = new TableComponent(rowData, columnNames);
        suppliersListPanel.add(table.getTableHeader());                        // 添加表头
        suppliersListPanel.setLayout(new BorderLayout(5, 5));
        JScrollPane scrollPane = new JScrollPane(table);                // 将表格添加到滚动面板中
        suppliersListPanel.add(scrollPane);

        // 用户信息管理界面
        JPanel suppliersMsgPanel = new JPanel();
        suppliersMsgPanel.setBorder(BorderFactory.createTitledBorder("供应商信息管理"));
        suppliersMsgPanel.setBounds(766, 54, 389, 661);
        add(suppliersMsgPanel);
        suppliersMsgPanel.setLayout(null);

        JLabel lblid = new JLabel("供应商名称");
        lblid.setBounds(37, 31, 54, 15);
        suppliersMsgPanel.add(lblid);

        suppliersName = new JTextField();
        //suppliersName.setEnabled(false);
        suppliersName.setBounds(101, 28, 263, 21);
        suppliersMsgPanel.add(suppliersName);
        suppliersName.setColumns(10);

        JLabel label_3 = new JLabel("供应商联系人姓名");
        label_3.setBounds(37, 72, 54, 15);
        suppliersMsgPanel.add(label_3);
        suppliersContactName = new JTextField();
        suppliersContactName.setBounds(101, 69, 263, 21);
        suppliersMsgPanel.add(suppliersContactName);

        JLabel label = new JLabel("联系邮箱");
        label.setBounds(37, 103, 54, 15);
        suppliersMsgPanel.add(label);

        suppliersEmailField = new JTextField();
        // suppliersEmailField.setEnabled(false);
        suppliersEmailField.setBounds(101, 110, 263, 21);
        suppliersMsgPanel.add(suppliersEmailField);
        suppliersEmailField.setColumns(10);
        //详细信息的边框
        JLabel labelId = new JLabel("供应商识别代码");
        labelId.setBounds(37, 134, 54, 15);
        suppliersMsgPanel.add(labelId);

        suppliersIdUpdate = new JTextField();
        suppliersIdUpdate.setEnabled(false);
        suppliersIdUpdate.setBounds(101, 151, 263, 21);
        suppliersMsgPanel.add(suppliersIdUpdate);
        suppliersIdUpdate.setColumns(10);


        /**
         * 修改按钮的操作
         */
        JButton button = new JButton("修改供应商信息");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (JOptionPane.showConfirmDialog(null, "确定修改？") == 0) {

                    //id为空
                    if (suppliersIdUpdate.getText() == null || "".equals(suppliersIdUpdate.getText().trim())) {
                        JOptionPane.showMessageDialog(null, "请选择一条要修改的信息", "提示", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    //封装数据，更新数据
                    Suppliers suppliers = new Suppliers();

                    suppliers.setContactname(suppliersContactName.getText());
                    suppliers.setSuppliername(suppliersName.getText());
                    suppliers.setContactemail(suppliersEmailField.getText());
                    suppliers.setSupplierid(Integer.valueOf(suppliersIdUpdate.getText()));
                    int i = suppliersService.updateSuppliersBySupplierID(suppliers);


                    if (i > 0) {
                        JOptionPane.showMessageDialog(null, "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                        clearField();
                        flushBtn.doClick();
                    } else {
                        JOptionPane.showMessageDialog(null, "修改失败", "提示", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
        button.setBounds(37, 607, 93, 23);
        suppliersMsgPanel.add(button);


        /**
         * 查找数据
         */
        // 设置表格监听事件
        ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.addListSelectionListener(new ListSelectionListener() {
            // 会响应两次，使用e.getValueIsAdjusting()判断，鼠标点击，getValueIsAdjusting() 返回True.
            // 鼠标释放,getValueIsAdjusting() 返回 False
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    String str = e.getSource().toString();
                    // 取出当前行
                    String indexStr = str.substring(str.lastIndexOf("{") + 1, str.lastIndexOf("}"));
                    if (str != null && !"".equals(str.trim()) && indexStr != null && !"".equals(indexStr.trim())) {
                        // 获取当前行序号
                        int index = Integer.parseInt(indexStr);
                        Integer suppliersId = (Integer) rowData[index][3];
                        Suppliers suppliersServiceById = suppliersService.getById(suppliersId);

                        if (suppliersServiceById == null) {
                            JOptionPane.showMessageDialog(null, "查找出错", "提示", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        // 封装数据
                        suppliersContactName.setText(suppliersServiceById.getContactname());
                        suppliersName.setText(suppliersServiceById.getSuppliername());
                        suppliersEmailField.setText(suppliersServiceById.getContactemail());
                        suppliersIdUpdate.setText(suppliersServiceById.getSupplierid().toString());

                    }
                }
            }
        });


    }

    /**
     * 更新供应商列表
     *
     * @param type  0 查找所有, 1 根据用户输入查找
     * @param input
     */
    private void updateSuppliersList(int type, String input) {
        if (type == 0) rowData = suppliersService.getAllSuppliers();
        if (type == 1) rowData = suppliersService.getSearchSuppliers(input);
        table.updateModel(rowData, columnNames);
        clearField();
    }

    /**
     * 清空输入框数据
     */
    private void clearField() {

        suppliersContactName.setText("");
        suppliersName.setText("");
        suppliersEmailField.setText("");
        suppliersIdUpdate.setText("");

    }
}
